package com.better.common.jwtauth.auth;

import com.better.backend.mqReceiverService.UserInfo.model.UserModel;
import com.better.common.base.ServiceResponse;
import com.better.common.jwtauth.TokenManager.RedisTokenManager;
import com.better.common.jwtauth.TokenManager.TokenManager;
import com.better.common.jwtauth.secruity.JwtAuthenticationRequest;
import com.better.common.jwtauth.secruity.JwtAuthenticationResponse;
import com.better.common.utils.ServiceResponseHandle;
import com.better.common.utils.redis.RedisUtils;
import com.google.code.kaptcha.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api(value = "登录授权信息", tags = "登录授权接口")
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TokenManager redisTokenManager;
    private static Log log = LogFactory.getLog(AuthController.class);

    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ServiceResponse<?> createAuthenticationToken(
            @RequestBody @Valid JwtAuthenticationRequest authenticationRequest, HttpServletRequest request) throws AuthenticationException {
        /*if (!checkValidateCode(request, authenticationRequest)) {
            return ServiceResponseHandle.failed("验证码错误!");
        }*/
        JwtAuthenticationResponse token = authService.login(authenticationRequest.getUserName(), authenticationRequest.getPassword());
        // Return the token
        return ServiceResponseHandle.success(token);
    }
    /**
     * 根据用户获取用户加密盐
    *@author:
    *@date :2018/2/2
    */
    @RequestMapping("getSalt")
    public ServiceResponse getSalt(@RequestBody JwtAuthenticationRequest authenticationRequest) {
        if (StringUtils.isEmpty(authenticationRequest.getUserName()))
            return ServiceResponseHandle.failed("PARAM_INVALID");
        return this.authService.getSaltByUname(authenticationRequest.getUserName());
    }

    /**
     * 验证码判断
     *
     * @param request
     * @return
     */
    protected boolean checkValidateCode(HttpServletRequest request, JwtAuthenticationRequest authenticationRequest) {
        Cookie[] cookies = request.getCookies();
        String token = "";
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if ((!StringUtils.isEmpty(c.getValue()) && c.getName().equals(Constants.KAPTCHA_SESSION_KEY))) {
                    token = c.getValue();
                }
            }
        }

        if (StringUtils.isEmpty(token)) {
            log.error("captchaCode不能为空！");
            return false;
        }
        if (!redisUtils.hasKey(token)) {
            log.error("验证码过期，请重新刷新！");
            return false;
        }
        //后续从redis 获取
        String code = redisUtils.getStr(token);
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        String user_verifyCode = authenticationRequest.getValidCode();// 获取用户输入验证码
        if (null == user_verifyCode || !code.equalsIgnoreCase(user_verifyCode)) {
            return false;
        }
        redisUtils.del(token);
        return true;
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ServiceResponse<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if (refreshedToken == null) {
            return ServiceResponseHandle.failed("刷新token失败");
        } else {
            return ServiceResponseHandle.success(new JwtAuthenticationResponse(refreshedToken));
        }
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ServiceResponse<?> register(@RequestBody UserModel addedUser) throws AuthenticationException {
        return ServiceResponseHandle.success(authService.register(addedUser));
    }
    @ApiOperation(value = "用户登出", notes = "用户登出接口")
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public ServiceResponse<?> logout(HttpServletRequest request) throws AuthenticationException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (StringUtils.isNotEmpty(authHeader) && authHeader.startsWith(tokenHead)) {
            final String authToken = authHeader.substring(tokenHead.length());
            redisTokenManager.deleteToken(authToken);
        }
        return ServiceResponseHandle.success("");

    }
}
